import json
import requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.core.files.storage import FileSystemStorage
from .models import Paper, Thesis, Reference
from django.shortcuts import get_object_or_404
from django.conf import settings
import os

# 大模型API配置
LLM_API_URL = "https://api.example.com/llm"
LLM_API_KEY = settings.LLM_API_KEY

@csrf_exempt
def user_register(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        
        if User.objects.filter(username=username).exists():
            return JsonResponse({'error': 'Username already exists'}, status=400)
        
        user = User.objects.create_user(username=username, password=password, email=email)
        return JsonResponse({'message': 'User registered successfully'}, status=201)
    return JsonResponse({'error': 'Method not allowed'}, status=405)

@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return JsonResponse({'message': 'User logged in successfully', 'user_id': user.id}, status=200)
        else:
            return JsonResponse({'error': 'Invalid credentials'}, status=401)
    return JsonResponse({'error': 'Method not allowed'}, status=405)

def user_logout(request):
    logout(request)
    return JsonResponse({'message': 'User logged out successfully'}, status=200)

@csrf_exempt
def paper_upload(request):
    if request.method == 'POST' and request.user.is_authenticated:
        title = request.POST.get('title')
        author = request.POST.get('author')
        publication = request.POST.get('publication')
        year = request.POST.get('year')
        abstract = request.POST.get('abstract')
        file = request.FILES.get('file')
        
        if not file:
            return JsonResponse({'error': 'No file uploaded'}, status=400)
        
        fs = FileSystemStorage()
        filename = fs.save(file.name, file)
        file_url = fs.url(filename)
        
        paper = Paper.objects.create(
            user=request.user,
            title=title,
            author=author,
            publication=publication,
            year=year,
            abstract=abstract,
            file=file_url,
            content=extract_text_from_pdf(file_url)  # 假设存在这个函数用于从PDF提取文本
        )
        
        return JsonResponse({'message': 'Paper uploaded successfully', 'paper_id': paper.id}, status=201)
    return JsonResponse({'error': 'Method not allowed or user not authenticated'}, status=405)

def paper_list(request):
    if request.method == 'GET' and request.user.is_authenticated:
        papers = Paper.objects.filter(user=request.user)
        paper_list = []
        for paper in papers:
            paper_list.append({
                'id': paper.id,
                'title': paper.title,
                'author': paper.author,
                'publication': paper.publication,
                'year': paper.year,
                'abstract': paper.abstract,
                'upload_time': paper.upload_time.strftime('%Y-%m-%d %H:%M:%S')
            })
        return JsonResponse({'papers': paper_list}, status=200)
    return JsonResponse({'error': 'Method not allowed or user not authenticated'}, status=405)

@csrf_exempt
def literature_review_generate(request):
    if request.method == 'POST' and request.user.is_authenticated:
        data = json.loads(request.body)
        paper_ids = data.get('paper_ids', [])
        topic = data.get('topic', '')
        
        papers = Paper.objects.filter(id__in=paper_ids, user=request.user)
        if not papers:
            return JsonResponse({'error': 'No papers found'}, status=404)
        
        # 收集所有文献内容
        paper_contents = []
        for paper in papers:
            paper_contents.append({
                'title': paper.title,
                'content': paper.content
            })
        
        # 准备请求大模型的数据
        prompt = f"""
        你是一个专业的学术助手，请根据以下文献内容，生成一篇关于"{topic}"的文献综述。
        文献内容如下：
        {json.dumps(paper_contents)}
        
        请生成一篇结构清晰、逻辑连贯的文献综述，包括研究背景、现状、主要观点、研究方法、研究成果和研究不足等方面。
        """
        
        # 调用大模型API
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {LLM_API_KEY}'
        }
        payload = {
            'prompt': prompt,
            'max_tokens': 2000,
            'temperature': 0.7
        }
        
        try:
            response = requests.post(LLM_API_URL, headers=headers, json=payload)
            response.raise_for_status()
            review_content = response.json().get('content', '')
            
            # 保存生成的文献综述
            thesis = Thesis.objects.create(
                user=request.user,
                title=f'文献综述：{topic}',
                structure='引言、研究现状、研究方法、研究成果、研究不足、结论',
                content=review_content
            )
            
            return JsonResponse({'message': 'Literature review generated successfully', 'thesis_id': thesis.id, 'content': review_content}, status=200)
        except requests.exceptions.RequestException as e:
            return JsonResponse({'error': f'Failed to generate literature review: {str(e)}'}, status=500)
    
    return JsonResponse({'error': 'Method not allowed or user not authenticated'}, status=405)

# 其他API视图函数...